import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class Log {
    private static Logger logger;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static {
        try {
            logger = Logger.getLogger("CinemaSystemLog");
            logger.setUseParentHandlers(false);
            String dateDir = DATE_FORMAT.format(new Date());
            File logDir = new File("logs/" + dateDir);
            if (!logDir.exists()) {
                logDir.mkdirs();
            }
            String logFilePath = logDir.getPath() + "/system.log";
            FileHandler fileHandler = new FileHandler(logFilePath, true);
            fileHandler.setFormatter(new Formatter() {
                @Override
                public String format(LogRecord record) {
                    return String.format("[%s] [%s] %s - %s%n", TIME_FORMAT.format(new Date(record.getMillis())), record.getSourceClassName(),record.getLevel(), record.getMessage());
                }
            });
            logger.addHandler(fileHandler);
            logger.setLevel(Level.INFO);
        } catch (IOException e) {
            System.err.println("日志初始化失败：" + e.getMessage());
        }
    }
    public static void info(String operator, String operation, String detail) {
        logger.log(Level.INFO, String.format("[操作人：%s] %s：%s", operator, operation, detail), operator);
    }
    public static void warning(String operator, String operation, String errorMsg) {
        logger.log(Level.WARNING, String.format("[操作人：%s] %s失败：%s", operator, operation, errorMsg));
    }
    public static void error(String operator, String operation, Exception exception) {
        logger.log(Level.SEVERE, String.format("[操作人：%s] %s发生错误：%s", operator, operation, exception.getMessage()), exception);
    }
}
